<!-- 我的购物车 -->
<template>
  <div v-loading="loading">
    <template v-if="goodsData.length > 0">
      <div v-for="(shop, index) in goodsData" :key="index" class="shoppingCart box gl_mb_20">
        <el-row type="flex" justify="space-between">
          <el-col class="title" :span="20">
            <span>商家{{ index + 1 }}：</span>
            <span class="hover_name gl_pointer" @click="toStore(shop.storeId)">{{ shop.storeName }}</span>
          </el-col>
          <el-col class="title gl_pointer" :span="2">
            <span class="del_more" @click="removeMore(index)">批量删除</span>
          </el-col>
        </el-row>
        <el-table ref="table" class="gl_table_noBorder gl_mb_5" :data="shop.items" size="mini" @selection-change="handleSelection($event, index)">
          <el-table-column type="selection" :width="60" />
          <el-table-column label="商品信息">
            <template slot-scope="{ row }">
              <div>
                <div class="img_box gl_dis_ib gl_middle">
                  <img :src="getStaticPhotoUrl(row.imageUrl)" alt="" style="width:100%; height:100%">
                </div>
                <div :title="row.productName" class="gl_dis_ib gl_middle gl_mx_10 gl_ellipsis gl_pointer hover_name" style="width: 280px" @click="toStore(shop.storeId, row.productId)">{{ row.productName }}</div>
                <div class="gl_dis_ib gl_middle">{{ row.color }} {{ row.size }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价/数量" :width="140">
            <template slot-scope="{ row }">
              <p>¥{{ (row.price / 100).toFixed(2) }}</p>
              <p>X{{ row.count }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="小计" :width="140">
            <template slot-scope="{ row }">
              ¥{{ (row.amount / 100).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" :width="100">
            <template slot-scope="{ row }">
              <el-button type="text" @click="remove(row)">
                <span style="color: #595959">删除</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="space-between">
          <el-col :span="6">
            <el-checkbox v-model="shop.checkAll" class="gl_mt_15" :indeterminate="shop.isIndeterminate" style="margin-left: 23px" label="全选" @change="selAll(index)" />
          </el-col>
          <el-col :span="12" align="right">
            <div class="gl_dis_ib gl_middle gl_fs_14" style="color: #595959">
              <span>已选择{{ shop.select }}件商品</span>
              <span class="gl_dis_ib gl_pr_20" style="width: 160px">总价：<span class="gl_color_error gl_ft_weight">¥{{ (shop.amount / 100).toFixed(2) }}</span></span>
            </div>
            <div class="gl_dis_ib gl_middle gl_ml_5">
              <el-button class="payment" @click="toSettlement(index)">
                <span>去结算</span>
              </el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </template>
    <div v-else class="gl_noData">
      <p>暂无数据</p>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import {
  api_GET_MallStoreId, // 店铺信息
  api_GET_MallShoppingCart, // 获取
  api_DELETE_MallShoppingCart // 删除
} from '@/extend/api/shoppingmallswaggerApi/app.js';
import {
} from '@/lib/form/shoppingmall/swaggerForm.js';
export default {
  data() {
    return {
      loading: false,
      goodsData: [],
      selection: [], // 选中
      goodsIds: [] // 结算的商品id
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    })
  },
  created() {
    this.getDict();
    this.getDictByType(['district']);
    this.getGoods();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType', setSettlementGoods: 'app/setSettlementGoods' }),
    // 获取
    getGoods() {
      const that = this;
      that.loading = true;
      api_GET_MallShoppingCart().then(res => {
        let goods = res || [];
        if (goods.length > 0) {
          goods = goods.map(item => {
            return { ...item, select: 0, amount: 0, checkAll: false, isIndeterminate: false };
          });
        }
        that.goodsData = goods;
        that.loading = false;
      }, error => {
        that.loading = false;
        that.$message({ type: 'error', message: '获取购物车列表失败！' + (error.error && error.error.message || '') });
      });
    },
    // 多选
    handleSelection(val, index) {
      if (val.length < this.goodsData[index].items.length && val.length > 0) {
        this.goodsData[index].isIndeterminate = true;
      } else if (val.length === this.goodsData[index].items.length) {
        this.goodsData[index].isIndeterminate = false;
        this.goodsData[index].checkAll = true;
      } else if (val.length === 0) {
        this.goodsData[index].isIndeterminate = false;
        this.goodsData[index].checkAll = false;
      }
      let sum = 0;
      this.goodsIds[index] = [];
      for (let i = 0; i < val.length; i++) {
        sum += val[i].amount;
        this.goodsIds[index].push(val[i].id);
      }
      this.selection[index] = val;
      this.goodsData[index].select = val.length;
      this.goodsData[index].amount = sum;
    },
    // 全选
    selAll(index) {
      if (this.selection[index] && (this.selection[index].length < this.goodsData[index].items.length)) {
        this.goodsData[index].checkAll = false;
      } else {
        this.goodsData[index].checkAll = true;
      }
      this.$refs.table[index].toggleAllSelection();
    },
    // 删除
    remove(row) {
      const that = this;
      this.$confirm(`您确定要删除此商品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = [row.id];
        const form = {
          RegisterId: null,
          DeletedIds: id
        };
        api_DELETE_MallShoppingCart(form).then(res => {
          that.$message({ type: 'success', message: '删除成功' });
          that.getGoods();
        }, error => {
          that.$message({ type: 'error', message: '删除失败！' + (error.error && error.error.message || '') });
        });
      }).catch(() => {});
    },
    // 批量删除
    removeMore(index) {
      const that = this;
      if (this.goodsIds[index].length > 0) {
        this.$confirm(`您确定要删除吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const form = {
            RegisterId: null,
            DeletedIds: that.goodsIds[index]
          };
          api_DELETE_MallShoppingCart(form).then(res => {
            that.$message({ type: 'success', message: '删除成功' });
            that.getGoods();
          }, error => {
            that.$message({ type: 'error', message: '删除失败！' + (error.error && error.error.message || '') });
          });
        }).catch(() => {});
      } else {
        this.$message({ type: 'warning', message: '请先勾选商品！' });
      }
    },
    // 去结算
    toSettlement(index) {
      if (this.goodsIds[index] && this.goodsIds[index].length > 0) {
        this.setSettlementGoods(this.goodsIds[index]);
        if (this.$route.path.indexOf('shoppingCart') !== -1) {
          this.$router.push({
            path: 'settlement',
            query: { last: 'shoppingCart' }
          });
        } else {
          this.$router.push({
            name: 'MyCartSettlement',
            query: { last: 'shoppingCart' }
          });
        }
      } else {
        this.$message({ type: 'warning', message: '请选择商品' });
      }
    },
    // 去往店铺
    toStore(storeId, productId) {
      api_GET_MallStoreId(storeId).then(res => {
        const store = res;
        var a = document.createElement('a');
        var event = new MouseEvent('click');
        a.href = `${location.origin}/mall.html#/home/${store.route + (store.tenantId ? '_' + store.tenantId : '') + '_plat'}/info/${productId || ''}`;
        a.target = '_blank';
        a.dispatchEvent(event);
      });
    },
    // 获取图片地址
    getStaticPhotoUrl(relativeUrl) {
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    }
  }
};
</script>

<style scoped>
.box {
  border-radius: 8px;
  box-shadow: 0px 10px 36px 0px rgba(0,0,0,0.08);
  padding: 5px 12px;
}
.title {
  height: 50px;
  font-size: 14px;
  font-weight: 500;
  color: #353434;
  line-height: 50px;
}
.el-table,.el-table /deep/ .el-table__body-wrapper {
  min-height: auto;
}
.shoppingCart .el-table {
  border-right: none !important;
  border-left: none;
}
.img_box {
  width: 62px;
  height: 62px;
  overflow: hidden;
}
.payment {
  width: 120px;
  height: 48px;
  background: #e33a3c;
  border-radius: 8px;
  color: #fff;
  font-size: 16px;
}
.hover_name:hover {
  color: #1B5CFF;
}
.del_more {
  padding: 4px 8px;
  border: 1px solid #e3e3e3;
  border-radius: 4px;
}
</style>
